import 'package:flutter/material.dart';
import '../../models/user_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/image_utils.dart';
import '../login/login_page.dart';
import 'security_settings_page.dart';
import 'follow_category_management_page.dart';
import 'skill_management_page.dart';
import 'chat_history_page.dart';
import 'consultation_history_page.dart';
import 'user_profile_manage_page.dart';
import 'shared_resources_page.dart';

class ManagementCenterPage extends StatefulWidget {
  const ManagementCenterPage({super.key});

  @override
  State<ManagementCenterPage> createState() => _ManagementCenterPageState();
}

class _ManagementCenterPageState extends State<ManagementCenterPage> {
  final ApiService _apiService = ApiService();
  
  // 当前用户数据（从API加载）
  UserModel? _currentUser;
  bool _isLoadingUser = false;

  @override
  void initState() {
    super.initState();
    _loadCurrentUser();
  }

  /// 加载当前用户数据
  Future<void> _loadCurrentUser() async {
    setState(() => _isLoadingUser = true);
    
    try {
      // 获取当前用户ID
      final userId = await _apiService.getUserId();
      if (userId == null) {
        Logger.e('ManagementCenterPage', '无法获取用户ID');
        return;
      }
      
      Logger.d('ManagementCenterPage', '开始加载用户资料，用户ID: $userId');
      
      // 从API获取用户个人资料
      final profile = await _apiService.getUserProfile(userId);
      
      // 构建UserModel
      setState(() {
        _currentUser = UserModel(
          id: userId,
          username: profile.username ?? '用户',
          email: profile.email ?? '',
          avatar: profile.avatarUrl ?? '',
          location: '',
          bio: profile.signature ?? '',
          skills: [],
          createdAt: profile.createTime ?? DateTime.now(),
        );
      });
      
      Logger.d('ManagementCenterPage', '加载用户资料成功');
      Logger.d('ManagementCenterPage', '用户昵称: ${profile.nickname}');
      Logger.d('ManagementCenterPage', '头像URL: ${profile.avatarUrl}');
    } catch (e) {
      Logger.e('ManagementCenterPage', '加载用户资料失败: $e');
      // 设置默认用户数据
      setState(() {
        _currentUser = UserModel(
          id: 'default',
          username: '用户',
          email: '',
          avatar: '',
          location: '',
          bio: '',
          skills: [],
          createdAt: DateTime.now(),
        );
      });
    } finally {
      setState(() => _isLoadingUser = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('管理中心'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        actions: [
          // 退出登录按钮
          TextButton.icon(
            onPressed: () => _showLogoutDialog(),
            icon: const Icon(Icons.logout, color: Colors.white, size: 20),
            label: const Text(
              '退出登录',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          const SizedBox(width: 8),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息卡片
            _buildUserInfoCard(),
            const SizedBox(height: 20),

            // 功能分类
            _buildSectionTitle('账户管理'),
            _buildFunctionCard(
              icon: Icons.person,
              title: '个人资料',
              subtitle: '编辑个人信息、头像等',
              onTap: () => _navigateToEditProfile(),
            ),
            _buildFunctionCard(
              icon: Icons.security,
              title: '安全设置',
              subtitle: '密码修改、邮箱绑定、设备管理',
              onTap: () => _navigateToSecuritySettings(),
            ),

            const SizedBox(height: 20),
            _buildSectionTitle('社交管理'),
            _buildFunctionCard(
              icon: Icons.label,
              title: '关注标签管理',
              subtitle: '管理关注用户的分类标签',
              onTap: () => _navigateToFollowCategoryManagement(),
            ),
            _buildFunctionCard(
              icon: Icons.psychology,
              title: '技能标签管理',
              subtitle: '编辑个人技能标签和等级',
              onTap: () => _showUnderDevelopment('技能标签管理'),
            ),

            const SizedBox(height: 20),
            _buildSectionTitle('记录管理'),
            _buildFunctionCard(
              icon: Icons.chat,
              title: '聊天记录',
              subtitle: '查看历史聊天记录',
              onTap: () => _navigateToChatHistory(),
            ),
            _buildFunctionCard(
              icon: Icons.psychology,
              title: '咨询记录',
              subtitle: '查看历史咨询记录',
              onTap: () => _showUnderDevelopment('咨询记录'),
            ),
            _buildFunctionCard(
              icon: Icons.video_library,
              title: '可享资源',
              subtitle: '查看授权给我的视频集合',
              onTap: () => _navigateToSharedResources(),
            ),

            const SizedBox(height: 20),
            _buildSectionTitle('其他设置'),
            _buildFunctionCard(
              icon: Icons.notifications,
              title: '消息通知',
              subtitle: '设置消息提醒方式',
              onTap: () => _showNotificationSettings(),
            ),
            _buildFunctionCard(
              icon: Icons.privacy_tip,
              title: '隐私设置',
              subtitle: '设置个人信息可见性',
              onTap: () => _showPrivacySettings(),
            ),
            _buildFunctionCard(
              icon: Icons.help,
              title: '帮助与反馈',
              subtitle: '常见问题、意见反馈',
              onTap: () => _showHelpAndFeedback(),
            ),
            _buildFunctionCard(
              icon: Icons.info,
              title: '关于我们',
              subtitle: '版本信息、用户协议',
              onTap: () => _showAboutUs(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUserInfoCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Theme.of(context).primaryColor,
            Theme.of(context).primaryColor.withOpacity(0.8),
          ],
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          // 使用安全的头像加载工具
          _isLoadingUser
              ? const CircularProgressIndicator(color: Colors.white)
              : ImageUtils.safeAvatarImage(
                  _currentUser?.avatar,
                  size: 60,
                ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _currentUser?.username ?? '用户',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  _currentUser?.email ?? '',
                  style: const TextStyle(
                    color: Colors.white70,
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '注册时间：${_formatDate(_currentUser?.createdAt ?? DateTime.now())}',
                  style: const TextStyle(
                    color: Colors.white70,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: Colors.grey,
        ),
      ),
    );
  }

  Widget _buildFunctionCard({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            icon,
            color: Theme.of(context).primaryColor,
            size: 24,
          ),
        ),
        title: Text(
          title,
          style: const TextStyle(
            fontWeight: FontWeight.w500,
          ),
        ),
        subtitle: Text(
          subtitle,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
        trailing: const Icon(Icons.arrow_forward_ios, size: 16),
        onTap: onTap,
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  // 导航方法
  void _navigateToEditProfile() async {
    // 获取当前用户ID
    final userId = await _apiService.getUserId() ?? '1';
    
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => UserProfileManagePage(userId: userId),
      ),
    ).then((result) {
      // 如果从个人资料管理页面返回时带回了更新标志，刷新当前页面
      if (result == true) {
        // 重新加载用户数据
        _loadCurrentUser();
      }
    });
  }

  void _navigateToSecuritySettings() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const SecuritySettingsPage(),
      ),
    );
  }

  void _navigateToFollowCategoryManagement() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const FollowCategoryManagementPage(),
      ),
    );
  }

  void _navigateToSkillManagement() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const SkillManagementPage(),
      ),
    );
  }

  /// 显示功能开发中提示
  void _showUnderDevelopment(String featureName) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.construction, color: Colors.orange[700]),
            const SizedBox(width: 8),
            const Text('功能开发中'),
          ],
        ),
        content: Text('$featureName功能正在开发中，敬请期待！'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('知道了'),
          ),
        ],
      ),
    );
  }

  /// 导航到可享资源页面
  void _navigateToSharedResources() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const SharedResourcesPage(),
      ),
    );
  }

  void _navigateToChatHistory() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const ChatHistoryPage(),
      ),
    );
  }

  void _navigateToConsultationHistory() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const ConsultationHistoryPage(),
      ),
    );
  }

  void _showNotificationSettings() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('消息通知设置'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: Text('推送通知'),
              trailing: Switch(value: true, onChanged: null),
            ),
            ListTile(
              title: Text('声音提醒'),
              trailing: Switch(value: false, onChanged: null),
            ),
            ListTile(
              title: Text('震动提醒'),
              trailing: Switch(value: true, onChanged: null),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showPrivacySettings() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('隐私设置'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: Text('个人资料可见性'),
              subtitle: Text('所有人可见'),
              trailing: Icon(Icons.arrow_forward_ios, size: 16),
            ),
            ListTile(
              title: Text('在线状态'),
              subtitle: Text('好友可见'),
              trailing: Icon(Icons.arrow_forward_ios, size: 16),
            ),
            ListTile(
              title: Text('技能标签可见性'),
              subtitle: Text('所有人可见'),
              trailing: Icon(Icons.arrow_forward_ios, size: 16),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showHelpAndFeedback() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('帮助与反馈'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: Icon(Icons.help),
              title: Text('常见问题'),
            ),
            ListTile(
              leading: Icon(Icons.feedback),
              title: Text('意见反馈'),
            ),
            ListTile(
              leading: Icon(Icons.contact_support),
              title: Text('联系客服'),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _showAboutUs() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('关于我们'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('应用版本：1.0.0'),
            SizedBox(height: 8),
            Text('开发者：Matrix Team'),
            SizedBox(height: 8),
            Text('© 2024 Matrix. All rights reserved.'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  // 显示退出登录确认对话框
  void _showLogoutDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.logout, color: Colors.orange),
            SizedBox(width: 8),
            Text('退出登录'),
          ],
        ),
        content: const Text('确定要退出登录吗？退出后需要重新登录才能使用完整功能。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => _performLogout(),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('退出'),
          ),
        ],
      ),
    );
  }

  // 执行退出登录操作
  Future<void> _performLogout() async {
    try {
      // 关闭确认对话框
      Navigator.pop(context);

      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: Card(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('正在退出...'),
                ],
              ),
            ),
          ),
        ),
      );

      // 调用API服务退出登录
      final apiService = ApiService();
      await apiService.logout();

      // 等待一小段时间确保数据清除完成
      await Future.delayed(const Duration(milliseconds: 500));

      // 关闭加载提示
      if (mounted) {
        Navigator.pop(context);

        // 显示退出成功提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('已退出登录'),
            duration: Duration(seconds: 2),
            backgroundColor: Colors.green,
          ),
        );

        // 跳转到登录页面，并清除所有导航栈
        Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(
            builder: (context) => const LoginPage(),
          ),
          (route) => false, // 清除所有路由
        );
      }
    } catch (e) {
      // 关闭加载提示
      if (mounted) {
        Navigator.pop(context);

        // 显示错误提示
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('退出失败：$e'),
            duration: const Duration(seconds: 3),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}
